package com.moneyanalyzer.sms;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import android.telephony.SmsMessage;

import com.moneyanalyzer.model.Transaction;
import com.moneyanalyzer.type.TypeTransaction;

public class SMSParser {
	public static Transaction parser(SmsMessage sms){
		Transaction transaction = null;
		
		String smsContent = sms.getMessageBody();
		
		Pattern pData = Pattern.compile("\\d{2}/\\d{2}/\\d{2}");
		Pattern pTime = Pattern.compile("\\d{2}:\\d{2}");
		Pattern pValue = Pattern.compile("\\d*,\\d{2}");
		Matcher mData = pData.matcher(smsContent);
		Matcher mTime = pTime.matcher(smsContent);
		Matcher mValue = pValue.matcher(smsContent);
		
		String strDate = null;
		if(mData.find())
			strDate = mData.group(0);
		
		String strTime = null;
		if(mTime.find())
			strTime = mTime.group(0);
		
		String value = null;
		if(mValue.find())
			value = mValue.group(0).replace(",", ".");
		
		TypeTransaction typeTransaction = null;
		if(smsContent.contains("deb.")){
			typeTransaction = TypeTransaction.DEBT;
		}
		
		String description = null;
		String[] auxSplit = smsContent.split("\\.");
		if(auxSplit.length>0){
			description = auxSplit[(auxSplit.length-1)];
			if(Character.isWhitespace(description.charAt(0)))
				description = description.substring(1);
		}
		if(description != null && typeTransaction != null && value != null 
				&& smsContent != null && sms.getOriginatingAddress() != null 
				&& strDate != null && strTime != null){
			transaction = new Transaction();
			transaction.setDescription(description);
			transaction.setTypeTransaction(typeTransaction);
			transaction.setValue(Float.valueOf(value));
			transaction.setSmsContent(smsContent);
			transaction.setOriginatingAddress(sms.getOriginatingAddress());
			try {
				Date dateTransaction = new SimpleDateFormat("dd/MM/yy HH:mm").parse(strDate+" "+strTime);
				transaction.setDate(dateTransaction.getTime());
			} catch (ParseException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		
		return transaction;
	}
}
